package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        //校验参数
        if (dto.getEquipmentId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户手机号和密码是否为空
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getStatus, 0)
                    .eq(ApUser::getPhone, dto.getPhone())
            );
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "请检查手机号");
            }
            //获取手机库密码做对比
            String dbPwd = apUser.getPassword();
            String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (!dbPwd.equals(newPwd)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号或密码不正确");
            }
            //创建map集合，封装数据，生成Token令牌
            Map<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        } else {
            //直接通过设备ID登录
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
